// 使用原生fetch API封装请求
class Request {
  constructor(baseURL, timeout = 10000) {
    this.baseURL = baseURL
    this.timeout = timeout
    this.defaultHeaders = {
      'Content-Type': 'application/json',
    }
  }

  // 获取认证头
  getAuthHeader() {
    const token = localStorage.getItem('token')
    console.log('获取认证头，当前token:', token)
    const authHeader = token ? { Authorization: `Bearer ${token}` } : {}
    console.log('认证头:', authHeader)
    return authHeader
  }

  // 请求拦截器
  requestInterceptor(url, options) {
    console.log('📤 发送请求:', options.method || 'GET', url)
    if (options.body) {
      console.log('📦 请求数据:', JSON.parse(options.body))
    }

    return {
      ...options,
      headers: {
        ...this.defaultHeaders,
        ...this.getAuthHeader(),
        ...options.headers,
      },
    }
  }

  // 响应拦截器
  async responseInterceptor(response) {
    console.log('📥 响应状态码:', response.status)

    let data
    try {
      data = await response.json()
      console.log('📦 响应数据:', data)
    } catch {
      // 忽略错误，继续处理文本响应
      data = await response.text()
      console.log('📦 响应内容:', data)
    }

    if (!response.ok) {
      // 对于 401 错误，清除本地 token
      if (response.status === 401) {
        localStorage.removeItem('token')
        console.log('401错误，已清除本地token')
      }
      throw new Error(`HTTP Error: ${response.status} - ${response.statusText}`)
    }

    return data
  }

  // 超时控制
  async fetchWithTimeout(url, options) {
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), this.timeout)

    try {
      const response = await fetch(url, {
        ...options,
        signal: controller.signal,
      })
      clearTimeout(timeoutId)
      return response
    } catch (error) {
      clearTimeout(timeoutId)
      if (error.name === 'AbortError') {
        throw new Error('请求超时')
      }
      throw error
    }
  }

  // 通用请求方法
  async request(endpoint, options = {}) {
    const url = `${this.baseURL}${endpoint}`
    const interceptedOptions = this.requestInterceptor(endpoint, options)

    try {
      const response = await this.fetchWithTimeout(url, interceptedOptions)
      const data = await this.responseInterceptor(response)
      return data
    } catch (error) {
      console.error('❌ 请求错误:', error)
      throw error
    }
  }

  // GET请求
  async get(endpoint, options = {}) {
    return this.request(endpoint, {
      ...options,
      method: 'GET',
    })
  }

  // POST请求
  async post(endpoint, data, options = {}) {
    return this.request(endpoint, {
      ...options,
      method: 'POST',
      body: JSON.stringify(data),
    })
  }

  // PUT请求
  async put(endpoint, data, options = {}) {
    return this.request(endpoint, {
      ...options,
      method: 'PUT',
      body: JSON.stringify(data),
    })
  }

  // DELETE请求
  async delete(endpoint, options = {}) {
    return this.request(endpoint, {
      ...options,
      method: 'DELETE',
    })
  }
}

// 创建实例
const request = new Request('http://127.0.0.1:5000')

export default request
